package com.jt.SecurityMain;

import com.alibaba.fastjson.JSON;
import com.jt.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 定义全局异常处理，实现认证AuthenticationEntryPoint接口
 *
 * */
@Slf4j
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
      try{
          Result result=new Result(401,null,"用户认证失败请查询登陆");
          String JSONString = JSON.toJSONString(result);
          response.setStatus(200);
          response.setCharacterEncoding("UTF-8");
          response.setContentType("application/json");
          response.getWriter().print(JSONString);
      }catch (Exception e){
          e.printStackTrace();
          log.error(e.toString());
      }

    }
}
